package com.example.boot.controller;

import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.fastjson.JSON;
import com.example.common.Result;
import com.example.common.enums.KeyEnum;
import com.example.common.enums.RedisFileConstant;
import com.example.common.websocket.WebSocketServe;
import com.example.pojo.utils.Weather;
import com.example.pojo.vo.TreeData;
import com.example.service.EChartsService;
import com.example.service.EntrustService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @author ding
 * @since 2024/7/9
 */
@RestController
@RequestMapping("/echarts")
@Slf4j
@Api(tags = "echats表相关数据")
public class EChartsController {

    @Autowired
    private EntrustService entrustService;

    @Autowired
    private EChartsService eChartsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WebSocketServe webSocketServe;

    @ApiOperation("树状图显示信息")
//    @PreAuthorize("hasAuthority('ECHARTS_DATA')")
    @GetMapping("/projectTree/{id}")
    public Result treeData(@PathVariable Integer id){
        TreeData[] tree = new TreeData[1];

//        tree[0] = entrustService.treeData(id);

        return Result.success(entrustService.treeData(id));
    }

    /**
     * 根据团队id获取该团队不同时间负责项目的开销
     */
    @ApiOperation("3D柱状图数据")
//    @PreAuthorize("hasAuthority('ECHARTS_DATA')")
    @GetMapping("/costData/{id}")
    public Result threeDData(@PathVariable Integer id) {
        eChartsService.threeDData(id);
        return Result.success();
    }

    @ApiOperation("获取当前登录者的天气信息")
//    @PreAuthorize("hasAuthority('ECHARTS_DATA')")
    @GetMapping("/weather")
    public Result weatherDate() {
        Weather weather = eChartsService.weatherDate();
        return Result.success(weather);
    }

    /**
     * 获取今日访问量数据
     */
//    @PreAuthorize("hasAuthority('ECHARTS_DATA')")
    @GetMapping("/uvCount")
    public Result getUV() {
        Long size = redisTemplate.opsForHyperLogLog().size(KeyEnum.UV);
        return Result.success(size);
    }

    /**
     * 获取当前在线人数
     */
//    @PreAuthorize("hasAuthority('ECHARTS_DATA')")
    @GetMapping("/onlineCount")
    public Result getOnline() {
        Long online = redisTemplate.opsForSet().size(KeyEnum.ONLINE);

        return Result.success(online);
    }

    @ApiOperation("获取一定时间内发布单位发布的项目数据")
    @GetMapping("/getEntrustCount")
    public Result getEntrustCount() {
        Map<String, Object> entrustCount = eChartsService.getEntrustCount();
        return Result.success(entrustCount);
    }

    @ApiOperation("获取相关后台营业数据")
    @GetMapping("/getReportData")
    public Result getReportData(){
        Map<String, Object> reportData = eChartsService.getReportData();
        return Result.success(reportData);
    }

    //导出后台数据
    @GetMapping("/exportBusiness")
    public Result exporBusiness(HttpServletResponse response) {
        Map<String, Object> map = eChartsService.getReportData();

        //组装数据至Excel中 XSSFWorkbook
        String reportDate = (String) map.get("reportDate");
        Long todayNewMember = (Long) map.get("todayNewMember");
        Long totalMember = (Long) map.get("totalMember");
        Long thisWeekNewMember = (Long) map.get("thisWeekNewMember");
        Long thisMonthNewMember = (Long) map.get("thisMonthNewMember");
        Long todayNewProject = (Long) map.get("todayNewProject");
        Long todayCompleteNumber = (Long) map.get("todayCompleteNumber");
        Long thisWeekNewNumber = (Long) map.get("thisWeekNewNumber");
        Long thisWeekCompleteNumber = (Long) map.get("thisWeekCompleteNumber");
        Long thisMonthNewNumber = (Long) map.get("thisMonthNewNumber");
        Long thisMonthCompleteNumber = (Long) map.get("thisMonthCompleteNumber");
        List<Map<String, Object>> hotTeam = (List<Map<String, Object>>) map.get("hotTeam");

        //组装数据到Excel对应的位置
        ClassPathResource classPathResource = new ClassPathResource("/template/report_template.xlsx");
        try(
                //组装数据至Excel中
                InputStream inputStream = classPathResource.getStream();
                XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
                ServletOutputStream out = response.getOutputStream();
        ){
            XSSFSheet sheet = workbook.getSheetAt(0);

            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayNewProject);//今日新增项目数
            row.getCell(7).setCellValue(todayCompleteNumber);//今日完成项目数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekNewNumber);//本周新增项目数
            row.getCell(7).setCellValue(thisWeekCompleteNumber);//本周完成项目数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthNewNumber);//本月新增项目数
            row.getCell(7).setCellValue(thisMonthCompleteNumber);//本月完成项目数

            int rowNum = 12;
            for(Map<String, Object> hotTeamMap : hotTeam){//热门套餐
                String name = (String) hotTeamMap.get("name");
                Long project_count = (Long) hotTeamMap.get("project_count");
                BigDecimal proportion = (BigDecimal) hotTeamMap.get("proportion");
                row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(project_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }

            //通过输出流进行文件下载
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            workbook.write(out);
            out.flush();
            return null;
        }catch(Exception e){
            e.printStackTrace();
        }
        return  Result.success();
    }

}
